﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace RestFullChatAJAX.Models
{
    public class ConnectHelper
    {
        private static String _connectString = @"Data Source=.\SQLEXPRESS; AttachDbFilename="
         + HttpContext.Current.Server.MapPath("~/")
         + @"App_Data\ChatAjaxDB.mdf; Integrated Security=True; User Instance=True";
        private static String _selectCommand = "Select * from Account";
        private static SqlConnection _connection = null;
        private static SqlDataAdapter accessHelper = null;

        public static DataTable KetnoiCSDL()
        {
            try
            {
                if (null == accessHelper)
                {
                    _connection = new SqlConnection(_connectString);
                    accessHelper = new SqlDataAdapter(_selectCommand, _connection);
                    SqlCommandBuilder builder = new SqlCommandBuilder(accessHelper);
                }
                if (_connection.State.ToString() == "Closed")
                    _connection.Open();
                DataTable accountTB = new DataTable();
                accountTB.Clear();
                accessHelper.Fill(accountTB);
                return accountTB;
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return null;
        }

        public static void DongKetNoi()
        {
            if (null != _connection)
            {
                accessHelper.Dispose();
                accessHelper = null;
                _connection.Close();
                _connection.Dispose();
                _connection = null;
            }
        }

        public static void Luu(DataTable accountTB)
        {
            accessHelper.Update(accountTB);
        }
    }
}